package com.witframework.baseapp;


import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.hsqldb.Server;

import com.witframework.core.ApplicationProperties;

public class HSqlListener implements ServletContextListener {
	private Server server;
	
	public void contextDestroyed(final ServletContextEvent evt) { 
		if(server!=null)
			server.shutdown();		
	}	
	public void contextInitialized(final ServletContextEvent evt) {	
		String database=ApplicationProperties.getProperty("jdbc.database");
		if(database!=null&&database.equals("hsql")){
			server = new Server();
			String path = evt.getServletContext().getRealPath(ApplicationProperties.getProperty("database.path","coredb"));		
			server.setDatabaseName(0, ApplicationProperties.getProperty("database.name","coredb"));
			server.setDatabasePath(0, path);
			server.setPort(Integer.parseInt(ApplicationProperties.getProperty("database.port","9001")));		
			server.setSilent(true);				
			Thread thread = new Thread(new Runnable() {
				public void run() {
					server.start();
				}
			});		
			thread.start();
		}
	}
	@Override
	public void finalize(){
		if(server!=null)
			server.shutdown();
	}
}